package com.hwxm.ltim.netty;

import com.hwxm.ltim.config.NettyConfig;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * WebSocket 通道初始化器
 */
@Component
public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    private NettyConfig nettyConfig;

    @Autowired
    private WebSocketHandler webSocketHandler;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        // HTTP 编解码器
        pipeline.addLast(new HttpServerCodec());
        // HTTP 聚合器
        pipeline.addLast(new HttpObjectAggregator(65536));
        // 支持大文件传输
        pipeline.addLast(new ChunkedWriteHandler());
        // 心跳检测：读超时60秒，写超时0秒，读写超时0秒
        pipeline.addLast(new IdleStateHandler(60, 0, 0, TimeUnit.SECONDS));
        // WebSocket 协议处理器
        pipeline.addLast(new WebSocketServerProtocolHandler(nettyConfig.getPath(), null, true, nettyConfig.getMaxFrameSize()));
        // 自定义消息处理器
        pipeline.addLast(webSocketHandler);
    }
}

